/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.util.AppSession;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class frmReporteProxLiquidacion extends javax.swing.JDialog {

    /* Services */
    ChequeServices chequeServices       = (ChequeServices)SpringUtils.getBean("chequeServices");
    CalendarioBancarioServices calendarServices   = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
    
    private static Logger log = Logger.getLogger(frmReporteProxLiquidacion.class);
    
    Map<String,Object> mapClienteLiquidacionImporte = new HashMap();
    public frmReporteProxLiquidacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        mostrarTotalesLiquidacionesPosibles();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelLiquidaciones = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        txtTotalLiquidPosibles = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        lblFechaLiquidacion = new javax.swing.JLabel();
        btnImprimirLiquidPosibles = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblLiquidPosibles = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Próxima liquidación :...");
        setResizable(false);

        panelLiquidaciones.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel4.setText("Total :");

        txtTotalLiquidPosibles.setEditable(false);
        txtTotalLiquidPosibles.setText("0");

        jLabel5.setText("Fecha liquidación:");

        lblFechaLiquidacion.setText("jLabel6");

        btnImprimirLiquidPosibles.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/printer.png"))); // NOI18N
        btnImprimirLiquidPosibles.setText("Imprimir");
        btnImprimirLiquidPosibles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirLiquidPosiblesActionPerformed(evt);
            }
        });

        tblLiquidPosibles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cliente", "Monto"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblLiquidPosibles.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jScrollPane3.setViewportView(tblLiquidPosibles);

        javax.swing.GroupLayout panelLiquidacionesLayout = new javax.swing.GroupLayout(panelLiquidaciones);
        panelLiquidaciones.setLayout(panelLiquidacionesLayout);
        panelLiquidacionesLayout.setHorizontalGroup(
            panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLiquidacionesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnImprimirLiquidPosibles)
                    .addGroup(panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panelLiquidacionesLayout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addGap(18, 18, 18)
                            .addComponent(txtTotalLiquidPosibles, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(panelLiquidacionesLayout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(lblFechaLiquidacion))
                        .addGroup(panelLiquidacionesLayout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        panelLiquidacionesLayout.setVerticalGroup(
            panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLiquidacionesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lblFechaLiquidacion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(panelLiquidacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTotalLiquidPosibles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnImprimirLiquidPosibles)
                .addGap(7, 7, 7))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelLiquidaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelLiquidaciones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private void mostrarTotalesLiquidacionesPosibles(){
        Calendar fechaProxLiquidacion = calendarServices.calcularFechaDeProximaLiquidacion();
        
        mapClienteLiquidacionImporte = chequeServices.getLiquidacionesPosiblesPorCadaCliente(fechaProxLiquidacion);
        if(mapClienteLiquidacionImporte.size() > 0){
            cargarTablaLiquidPosibles(mapClienteLiquidacionImporte);
        }
        
        lblFechaLiquidacion.setText(Formato.cambiarFechaAFormatoLocal(fechaProxLiquidacion.getTime()));
    }
    
    private void cargarTablaLiquidPosibles(Map<String,Object> mapita){
        double totalLiquidacionesPosiblesDelDia = 0;
        DefaultTableModel model     = (DefaultTableModel) tblLiquidPosibles.getModel();
        model.getDataVector().clear();
        
        for (Map.Entry<String, Object> entry : mapita.entrySet()) 
        { 
            model.addRow(new Object[]{entry.getKey(),Formato.decimalComaMilesConSigno(Double.parseDouble(entry.getValue().toString()))});
            totalLiquidacionesPosiblesDelDia += Double.parseDouble(entry.getValue().toString());
            
        }
        
        /*Total*/
        model.addRow(new Object[]{"Total",Formato.decimalComaMilesConSigno((totalLiquidacionesPosiblesDelDia))});
        
        
        TableColumnAdjuster tca = new TableColumnAdjuster(tblLiquidPosibles);
        tca.adjustColumns();
        tblLiquidPosibles.setModel(model);
        tblLiquidPosibles.repaint();
        txtTotalLiquidPosibles.setText(Formato.decimalComaMilesConSigno(totalLiquidacionesPosiblesDelDia));
    }
    
    
    private void btnImprimirLiquidPosiblesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirLiquidPosiblesActionPerformed
        try {
            MessageFormat header = new MessageFormat(UIMessages.getInfoMessage("liquidacionesPosibles_title")+"\n"+Formato.fechaDDMMYY(new Date()),new Locale("es","ES"));
            boolean imprimio = tblLiquidPosibles.print(JTable.PrintMode.NORMAL, header, null, true, null, true);
            if(imprimio){
                log.info("Imprimió reporte de Liquidaciones posibles...");
            }
        } catch (PrinterException ex) {
            log.error("Error al imprimir...",ex);
            log.error(ex.getMessage());
        } catch (HeadlessException ex) {
            log.error(ex.getMessage());
            log.error("Sin encabezado ...",ex);
        }
    }//GEN-LAST:event_btnImprimirLiquidPosiblesActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmReporteProxLiquidacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmReporteProxLiquidacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmReporteProxLiquidacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmReporteProxLiquidacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmReporteProxLiquidacion dialog = new frmReporteProxLiquidacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImprimirLiquidPosibles;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblFechaLiquidacion;
    private javax.swing.JPanel panelLiquidaciones;
    private javax.swing.JTable tblLiquidPosibles;
    private javax.swing.JTextField txtTotalLiquidPosibles;
    // End of variables declaration//GEN-END:variables
}
